package com.stooges.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author 张超
 * @date 2017/4/11
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    /**
     * 设置spring security对/和/login不拦截
     * 设置spring security的登录页面访问的路径为/login
     * 登录成功后转向/chat路径
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //除了/及/login外其他访问路径都需要经过权限验证
                .antMatchers("/","/login").permitAll()
                .anyRequest().authenticated()
                //添加登录页面及登录成功后返回的页面
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/chat")
                .permitAll()
                //登出全部权限
                .and()
                .logout().permitAll();
    }

    /**
     * 添加两个内存用户
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("wyf").password("wyf").roles("USER")
        .and().withUser("sky").password("sky").roles("USER");
    }

    /**
     * 访问静态文件不需要添加
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/static/**");
    }
}
